package com.example.dw;

import com.example.dw.domain.DsNodeSource;
import com.example.dw.service.DsNodeModelService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DwDataSourceManager {

    @Autowired
    private DsNodeModelService dsNodeModelService;

    private final Map<String, DataSource> dataSources = new HashMap<>();

    @PostConstruct
    public void init() {
        List<DsNodeSource> list=dsNodeModelService.list();
        if(list!=null && !list.isEmpty()) {
            for(DsNodeSource dsNodeModel:list){
                DataSource dataSource=createDataSource(dsNodeModel);
                dataSources.put(dsNodeModel.getModelNo(), dataSource);
            }
        }
    }

    public DataSource getDataSource(String modelNo) {
        return dataSources.get(modelNo);
    }

    private DataSource createDataSource(DsNodeSource model) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(model.getModelUrl());
        dataSource.setUsername(model.getModelUsername());
        dataSource.setPassword(model.getModelPassword());
        dataSource.setDriverClassName(model.getModelDriveClass());
        dataSource.setMaximumPoolSize(10);
        dataSource.setMinimumIdle(2);
        return dataSource;
    }
}
